import axios from "axios";
import { showLoadingToast, closeToast } from 'vant';

axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
// axios.defaults.withCredentials = true;
axios.defaults.timeout = 5000000;
// post请求头
// axios.defaults.headers['Content-Type'] = 'application/json';
axios.defaults.headers['x-requested-with'] = 'XMLHttpRequest';

axios.interceptors.request.use(
  (config) => {
    if (config.url != "/cashier/queryOrder/queryOrderState") {
      // let isDelay = config.url == "/cashier/quick/confirmH5"
      // let isDelay2 = config.url == "/cashier/quick/queryAgreementId"
      var time;
      switch (config.url) {
        case '/cashier/quick/confirmH5':
          time = 2000
          break;
        case '/cashier/quick/queryAgreementId':
          time = 0
          break;

        default:
          time = 5
          break;
      }
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        className: 'loading-toast',
        duration: time
      });
    }
    return config;
  },
  error => Promise.error(error),
);

axios.interceptors.response.use(
  async (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    }
    closeToast();
    return Promise.reject(response);
  },
  // 服务器状态码不是200的情况
  error => Promise.reject(error),
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// eslint-disable-next-line no-shadow
export function get(url, params, config) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
        ...config,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// eslint-disable-next-line no-shadow
export function post(url, params, config, exportExcel) {
  return new Promise((resolve, reject) => {
    // 确保请求头中包含 'Content-Type': 'application/json'
    const headers = {
      'Content-Type': 'application/json;charset=utf-8'
    };

    axios
      .post(url, params, { ...config, headers })
      // .post(url, params, config)
      .then((res) => {
        if (exportExcel) {
          resolve(res);
          return false;
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
